package com.jk.dmconsumer.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.jk.dmconsumer.config.AlipayConfig;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * 文件名称:OrderService
 *
 * @Description //TODO $
 * @Date $ $
 * 作者 郭英杰
 * Copyright (c) 2021, yuxy123@gmail.com All Rights Reserved.</pre>
 */
@Service
public class OrderService {

    /**
     * 退款
     * @param response
     * @param session
     * @throws IOException
     * @throws AlipayApiException
     */

    public void refund(HttpServletResponse response, HttpSession session) throws IOException, AlipayApiException {
        // 设置编码格式
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gateway, AlipayConfig.app_id, AlipayConfig.merchant_private_key,
                AlipayConfig.format, AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，必填
        String out_trade_no = new String("617ceee8-6fc3-4c10-b378-981aef219eb2");
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = Integer.toString(800);
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(UUID.randomUUID().toString());
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        out.println(result);
        //以下写自己的订单退款代码

    }


}
